package cn.gz.demo.ui;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import cn.gz.demo.BaseApplication;
import cn.gz.demo.R;
import cn.gz.demo.adapter.GreendaoUserAdapter;
import cn.gz.demo.dao.UserDao;
import cn.gz.demo.databinding.GreenDaoBinding;
import cn.gz.demo.dto.User;
import cn.gz.demo.ui.base.BaseActivity;
import cn.gz.demo.utils.ToastUtil;

/**
 * Created by Lyz on 2017/3/8.
 */
public class GreenDaoActivity extends BaseActivity {
    private GreenDaoBinding binding;
    private List<User> list = new ArrayList<>();
    private GreendaoUserAdapter adapter;
    private UserDao userDao = BaseApplication.getInstances().getDaoSession().getUserDao();
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_greendao);

        binding.content.setLayoutManager(new LinearLayoutManager(context));
        adapter = new GreendaoUserAdapter(context, list);
        binding.content.setAdapter(adapter);

        binding.save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = binding.name.getText().toString().trim();
                String age = binding.age.getText().toString().trim();
                String sex = binding.sex.getText().toString().trim();
                if (TextUtils.isEmpty(name) || TextUtils.isEmpty(age) || TextUtils.isEmpty(sex)) {
                    ToastUtil.showToast("数据不能为空");
                    return;
                }
                user = new User();
                user.setName(name);
                user.setAge(age);
                user.setSex(sex);
                userDao.insert(user);
            }
        });
        binding.search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.clear();
                list.addAll(userDao.queryBuilder().where(UserDao.Properties.Name.notEq(""), UserDao.Properties.Name.isNotNull()).list());
                adapter.notifyDataSetChanged();
            }
        });
    }
}
